package qky.api.service.impl;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import qky.api.entity.FirmEntity;
import qky.api.entity.TokenEntity;
import qky.api.entity.UserEntity;
import qky.api.service.FirmService;
import qky.api.service.TokenService;
import qky.common.exception.QkyException;
import qky.common.validator.Assert;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Service("userService")
public class UserServiceImpl extends UserServiceImplGen {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private FirmService firmService;

    @Override
    public UserEntity getByMobile(String mobile) {
        return this.dao.getByMobile(mobile);
    }

    @Override
    public Map<String, Object> login(String mobile, String password) {
        UserEntity user = getByMobile(mobile);
        Assert.isNull(user, "手机号或密码错误");

        //密码错误
        if(!user.getPassword().equals(DigestUtils.sha256Hex(password))){
            throw new QkyException("手机号或密码错误");
        }
        //是否认证
        if(user.getUserStatus()==0 || user.getUserStatus()==1) {
            throw new QkyException("客户信息还未认证");
        }
        //认证不通过
        if(user.getUserStatus()==4) {
            throw new QkyException("客户信息认证不通过");
        }
        //禁用
        if(user.getUserStatus()==3) {
            throw new QkyException("当前客户已被禁用");
        }
        //获取登录token
        TokenEntity tokenEntity = tokenService.createToken(user.getUserId());

        Map<String, Object> map = new HashMap<>(5);
        map.put("userId", user.getUserId());
        map.put("token", tokenEntity.getToken());
        map.put("expire", tokenEntity.getExpireTime().getTime() - System.currentTimeMillis());
        return map;
    }

    @Override
    public void register(UserEntity user, String company) {
        user.setNickName(user.getMobile());
        user.setUsername(user.getMobile());
        user.setCreateTime(new Date());
        user.setCreateBy("1");
        user.setUpdateTime(new Date());
        user.setUpdateBy("1");
        //        user.setUserStatus(0);
        user.setUserStatus(2); // 测试时开放
        user.setDeleted(0);
        save(user);

        FirmEntity firmEntity = new FirmEntity();
        firmEntity.setFirmName(company);
        firmEntity.setCreateBy(user.getUserId());
        firmEntity.setRegisterUserId(user.getUserId());
        firmEntity.setDeleted(0);
        firmEntity.setContact(user.getContacts());
        firmService.save(firmEntity);

    }
}
